from flask import Flask, render_template, request, redirect, url_for
import csv

app = Flask(__name__)

# 模拟的客户数据
customers = [
    {"customerID": "1", "customerName": "张三", "PID": "123456789", "telephone": "13800000000", "address": "北京市"},
    {"customerID": "2", "customerName": "李四", "PID": "987654321", "telephone": "13900000000", "address": "上海市"}
]

# 客户管理路由
@app.route('/customers')
def customer_management():
    return render_template('customers.html', customers=customers)

# 添加客户页面
@app.route('/add_customer', methods=['GET', 'POST'])
def add_customer():
    if request.method == 'POST':
        # 从表单获取数据
        customer_name = request.form['customerName']
        pid = request.form['PID']
        telephone = request.form['telephone']
        address = request.form['address']
        new_customer = {
            "customerID": str(len(customers) + 1),
            "customerName": customer_name,
            "PID": pid,
            "telephone": telephone,
            "address": address
        }
        customers.append(new_customer)
        return redirect(url_for('customer_management'))
    return render_template('add_customer.html')

# 导出客户数据为 CSV
@app.route('/export_customers')
def export_customers():
    with open('customers.csv', 'w', newline='', encoding='utf-8') as file:
        writer = csv.DictWriter(file, fieldnames=["customerID", "customerName", "PID", "telephone", "address"])
        writer.writeheader()
        for customer in customers:
            writer.writerow(customer)
    return redirect(url_for('customer_management'))

# 首页路由
@app.route('/')
def home():
    return render_template('home.html')

if __name__ == '__main__':
    app.run(debug=True)
